package com.lepu.app.fun.my;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;

import com.app.utils.LoginUtil;
import com.app.utils.ObserverConst;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.ui.wheel.OnWheelChangedListener;
import com.core.lib.ui.wheel.WheelView;
import com.core.lib.utils.EmojiFilter;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.widget.MyDialog;
import com.lepu.app.fun.my.bean.BeanMyAddressManage;
import com.lepu.app.main.adapter.CityWheelAdapter;
import com.lepu.app.main.adapter.DistrictWheelAdapter;
import com.lepu.app.main.adapter.ProvinceWheelAdapter;
import com.lepu.app.main.bean.BeanArea;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewRightButtonListener;
import com.lepu.pasm.R;

public class MyAddressActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, OnTopbarNewRightButtonListener,
		AsyncRequest {

	private boolean mIsNewAdd = false;
	private String mAID = "";
	private int mCurrentAddressCount = 0;

	public WheelView mWheelProvince, mWheelCity, mWheelQu;
	public int mProvinceValue, mCityValue,mDistrictValue;
	
	//ArrayList<BeanAreaProvince> mProvinces = null;
	String mAreaID = "0", mAreaName;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_address_activity);
		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	/**
	 * 初始化方法
	 */
	private void init() {

		BeanMyAddressManage item = null;
		Bundle data = getIntent().getExtras();
		if (data != null && data.size() > 0) {
			mIsNewAdd = data.getBoolean("IsNewAdd");
			item = (BeanMyAddressManage) data
					.getSerializable("BeanMyAddressManage");
			mCurrentAddressCount = data.getInt("CurrentAddressCount");
		}

		if(item == null)
		{
			return;
		}

		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setonTopbarNewLeftLayoutListener(this);
		topbar.setOnTopbarNewRightButtonListener(this);

		EditText nameEditText = (EditText) findViewById(R.id.nameEditText);
		EditText phoneEditText = (EditText) findViewById(R.id.phoneEditText);
		EditText youbianEditText = (EditText) findViewById(R.id.youbianEditText);
		TextView addressValueTextView = (TextView) findViewById(R.id.addressValueTextView);
		EditText addressEditText = (EditText) findViewById(R.id.addressEditText);

		nameEditText.setFilters(new InputFilter[] { new EmojiFilter(),
				new InputFilter.LengthFilter(10) });
		phoneEditText.setFilters(new InputFilter[] { new EmojiFilter(),
				new InputFilter.LengthFilter(20) });
		youbianEditText.setFilters(new InputFilter[] { new EmojiFilter(),
				new InputFilter.LengthFilter(6) });
		addressEditText.setFilters(new InputFilter[] { new EmojiFilter(),
				new InputFilter.LengthFilter(50) });// 50

		if (mIsNewAdd) {
			topbar.setTopbarTitle("新建收货人");
			topbar.setRightText("保存");
		} else {
			topbar.setTopbarTitle("编辑收货人");
			topbar.setRightText("保存");

			nameEditText.setText(item.ReceiverName);
			phoneEditText.setText(item.ReceiverPhone);
			youbianEditText.setText(item.ZipCode);
			addressEditText.setText(item.ReceiverAddress);

			String sheng = "";
			String shi = "";
			String qu = "";
			BeanArea beanArea = BeanArea.getAreaById(item.AreaID);

			if(beanArea != null)
			{
				String[] extraArray = beanArea.Extra.split(",");
				if(extraArray.length == 3)//0,1,2  省市区
				{
					sheng = BeanArea.getAreaById(extraArray[extraArray.length - 2]).Name;
					shi = BeanArea.getAreaById(extraArray[extraArray.length - 1]).Name;
					qu = beanArea.Name;
				}else{//0,1  省市
					sheng = BeanArea.getAreaById(extraArray[extraArray.length - 1]).Name;
					shi = beanArea.Name;
				}
			}else{
				sheng = "省、";
				shi = "市、";
				qu = "区";
			}

			StringBuffer sb = new StringBuffer();
			sb.append(sheng);
			sb.append("	");
			sb.append(shi);
			sb.append("	");
			sb.append(qu);
			sb.append("	");
			addressValueTextView.setText(sb.toString());

			mAID = item.AID;
		}

		ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView);
		scrollView.setOnTouchListener(new OnTouchListener() {

			@SuppressLint("ClickableViewAccessibility")
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				UtilityBase.closeSoftInput(MyAddressActivity.this);
				return false;
			}
		});
	}

	private void save() {
		EditText nameEditText = (EditText) findViewById(R.id.nameEditText);
		EditText phoneEditText = (EditText) findViewById(R.id.phoneEditText);
		EditText youbianEditText = (EditText) findViewById(R.id.youbianEditText);
		TextView addressValueTextView = (TextView) findViewById(R.id.addressValueTextView);
		EditText addressEditText = (EditText) findViewById(R.id.addressEditText);

		String name = nameEditText.getText().toString().trim();
		String phone = phoneEditText.getText().toString().trim();
		String youbianText = youbianEditText.getText().toString().trim();
		String addressValue = addressValueTextView.getText().toString().trim();// 所在地区
		String address = addressEditText.getText().toString().trim();

		if (TextUtils.isEmpty(name)) {
			UIHelper.showToast(this, "请输入收货人姓名");
			return;
		}

		if (name.length() < 2) {
			UIHelper.showToast(this, "请输入2-10个长度");
			return;
		}

		if (TextUtils.isEmpty(phone)) {
			UIHelper.showToast(this, "请输入联系方式");
			return;
		}

		if (phone.length() < 7 || phone.length() > 16) {
			UIHelper.showToast(this, "请您输入正确的联系方式");
			return;
		}

		if (TextUtils.isEmpty(youbianText)) {
			UIHelper.showToast(this, "请输入邮编");
			return;
		}

		if (TextUtils.isEmpty(addressValue)) {
			UIHelper.showToast(this, "请选择省市区");
			return;
		}

		if (TextUtils.isEmpty(address)) {
			UIHelper.showToast(this, "请输入详细地址");
			return;
		}

		Map<String, Object> map = new HashMap<String, Object>();
		try {
			JSONObject params = new JSONObject();
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());

			//
			params.put("ReceiverName", name);
			params.put("ReceiverPhone", phone);
			params.put("ReceiverAddress", address);

			params.put("ZipCode", youbianText);// 邮编
			params.put("AreaID", mAreaID);// 选择省市区的id

			if (!mIsNewAdd) {
				params.put("AID", mAID);
			} else {
				if (mCurrentAddressCount == 0) {
					params.put("IsDefault", "1");
				} else {
					params.put("IsDefault", "0");
				}
			}

			map.put("ht", params);
		} catch (Exception e) {
			e.printStackTrace();
		}

		String url = "";
		if (mIsNewAdd) {
			url = Setting.getSaveUserAddressUrl();
		} else {
			url = Setting.getUpdateUserAddressUrl();
		}

		showProgressDialog();
		ApiClient.http_post_main(url, map, null, this, "", true);
	}

	public void viewClick(View v) {
		int rid = v.getId();
		switch (rid) {
		case R.id.addressSelectLayout:

			selectAddress();
			break;

		default:
			break;
		}
	}
	
	private void getAreaInfo() {
        int provincePosition = mProvinceValue;
        int cityPosition = mCityValue;
        int districtPosition = mDistrictValue;
        
        BeanArea province;
		BeanArea city;
		BeanArea district;

//        province = mProvinces.get(provincePosition);
//        if (province.cityList.size() != 0) {
//            city = province.cityList.get(cityPosition);
//            mAreaID = city.cityID;
//            mAreaName = province.provinceName + "  " + city.cityName;
//            if (city.districtList.size() != 0) {
//                district = city.districtList.get(districtPosition);
//                mAreaID = district.districtID;
//                mAreaName = province.provinceName + "  "
//                        + city.cityName + "  "
//                        + district.districtName;
//            }
//        }

		ArrayList<BeanArea> provinceList = BeanArea.getAreaByExtra("0");//0,1,2
		String shiExtra = "0"+","+provinceList.get(provincePosition).Id;
		ArrayList<BeanArea> shiList = BeanArea.getAreaByExtra(shiExtra);

		province = provinceList.get(provincePosition);
		if (shiList != null && shiList.size() != 0) {
			city = shiList.get(cityPosition);
			mAreaID = String.valueOf(city.Id);
			mAreaName = province.Name + "  " + city.Name;

			String quExtra = shiExtra+","+shiList.get(cityPosition).Id;
			ArrayList<BeanArea> quList = BeanArea.getAreaByExtra(quExtra);

			if (quList != null && quList.size() != 0) {
				district = quList.get(districtPosition);
				mAreaID = String.valueOf(district.Id);
				mAreaName = province.Name + "  "
						+ city.Name + "  "
						+ district.Name;
			}
		}
        
        TextView addressValueTextView = (TextView) findViewById(R.id.addressValueTextView);
        addressValueTextView.setText(mAreaName);
    }

	@SuppressLint("InflateParams")
	private void selectAddress() {
		
		/**
		 * 暂时没有从数据库中取数据，是从assets中取的
		 */
		//mProvinces = BeanAreaProvince.getProvinceList(this);
		final ArrayList<BeanArea> provinceList = BeanArea.getAreaByExtra("0");//0,1,2
		String shiExtra = "0"+","+provinceList.get(mProvinceValue).Id;
		ArrayList<BeanArea> shiList = BeanArea.getAreaByExtra(shiExtra);
		String quExtra = shiExtra+","+shiList.get(mCityValue).Id;
		ArrayList<BeanArea> quList = BeanArea.getAreaByExtra(quExtra);
		
		final MyDialog myDialog = new MyDialog(this);
		View view = getLayoutInflater().inflate(
				R.layout.app_province_city_qu_dialog, null);

		mWheelProvince = (WheelView) view.findViewById(R.id.province);
		mWheelCity = (WheelView) view.findViewById(R.id.city);
		mWheelQu = (WheelView) view.findViewById(R.id.qu);

		// 根据屏幕密度来指定选择器字体的大小
		int textSize = UtilityBase.getTextNumberSize(this);

		mWheelProvince.TEXT_SIZE = textSize;
		mWheelCity.TEXT_SIZE = textSize;
		mWheelQu.TEXT_SIZE = textSize;

		// 省
		mWheelProvince.setAdapter(new ProvinceWheelAdapter(provinceList));// 设置"年"的显示数据
		mWheelProvince.setCyclic(false);// 可循环滚动
		mWheelProvince.setCurrentItem(mProvinceValue);// 初始化时显示的数据

		// 市
		mWheelCity.setAdapter(new CityWheelAdapter(shiList));
		mWheelCity.setCyclic(false);
		mWheelCity.setCurrentItem(mCityValue);

		// 区
		mWheelQu.setCyclic(false);
		mWheelQu.setAdapter(new DistrictWheelAdapter(quList));
		mWheelQu.setCurrentItem(mDistrictValue);

		OnWheelChangedListener provinceListner = new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				mProvinceValue = newValue;
//				if (mProvinces.get(newValue).cityList.size() != 0) {
//					mWheelCity.setAdapter(new CityWheelAdapter(mProvinces.get(
//							newValue).cityList));
//					mWheelCity.setCurrentItem(0);
//					Log.i("hz", "has city");
//					if (mProvinces.get(newValue).cityList.get(0)
//							.districtList.size() != 0) {
//						mWheelQu.setAdapter(new DistrictWheelAdapter(mProvinces
//								.get(newValue).cityList.get(0)
//								.districtList));
//						mWheelQu.setCurrentItem(0);
//					} else {
//						ArrayList<BeanAreaDistrict> array = new ArrayList<BeanAreaDistrict>();
//						BeanAreaDistrict district = new BeanAreaDistrict();
//						district.districtName = mProvinces.get(newValue)
//								.cityList.get(0).cityName;
//						array.add(district);
//						mWheelQu.setAdapter(new DistrictWheelAdapter(array));
//						mWheelQu.setCurrentItem(0);
//					}
//
//				} else {
//					Log.i("hz", "no city");
//					ArrayList<BeanAreaCity> array = new ArrayList<BeanAreaCity>();
//					BeanAreaCity city = new BeanAreaCity();
//					city.cityName = mProvinces.get(newValue).provinceName
//							;
//					array.add(city);
//
//					mWheelQu.setAdapter(new CityWheelAdapter(array));
//					mWheelQu.setCurrentItem(0);
//					ArrayList<BeanAreaDistrict> disArray = new ArrayList<BeanAreaDistrict>();
//					BeanAreaDistrict district = new BeanAreaDistrict();
//					district.districtName = mProvinces.get(newValue)
//							.provinceName;
//					disArray.add(district);
//					mWheelQu.setAdapter(new DistrictWheelAdapter(disArray));
//					mWheelQu.setCurrentItem(0);
//				}
				String shiExtraTemp = "0"+","+provinceList.get(mProvinceValue).Id;
				ArrayList<BeanArea> shiListTemp = BeanArea.getAreaByExtra(shiExtraTemp);

				if (shiListTemp != null && shiListTemp.size() != 0) {
					mWheelCity.setAdapter(new CityWheelAdapter(shiListTemp));
					mWheelCity.setCurrentItem(0);

					String quExtra = shiExtraTemp+","+shiListTemp.get(0).Id;
				    ArrayList<BeanArea> quListTemp = BeanArea.getAreaByExtra(quExtra);

					Log.i("hz", "has city");
					if (quListTemp != null && quListTemp.size() != 0) {
						mWheelQu.setAdapter(new DistrictWheelAdapter(quListTemp));
						mWheelQu.setCurrentItem(0);
					} else {
						ArrayList<BeanArea> array = new ArrayList<BeanArea>();
						BeanArea district = new BeanArea();
						district.Name = shiListTemp.get(0).Name;
						array.add(district);
						mWheelQu.setAdapter(new DistrictWheelAdapter(array));
						mWheelQu.setCurrentItem(0);
					}

				} else {
					Log.i("hz", "no city");
					ArrayList<BeanArea> array = new ArrayList<BeanArea>();
					BeanArea city = new BeanArea();
					city.Name = provinceList.get(newValue).Name
					;
					array.add(city);

					mWheelQu.setAdapter(new CityWheelAdapter(array));
					mWheelQu.setCurrentItem(0);
					ArrayList<BeanArea> disArray = new ArrayList<BeanArea>();
					BeanArea district = new BeanArea();
					district.Name = provinceList.get(newValue)
							.Name;
					disArray.add(district);
					mWheelQu.setAdapter(new DistrictWheelAdapter(disArray));
					mWheelQu.setCurrentItem(0);
				}

			}
		};

		OnWheelChangedListener cityListner = new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				mCityValue = newValue;
//				if (mProvinces.get(mProvinceValue).cityList.get(newValue)
//						.districtList.size() != 0) {
//					mWheelQu.setAdapter(new DistrictWheelAdapter(mProvinces
//							.get(mProvinceValue).cityList.get(newValue)
//							.districtList));
//					mWheelQu.setCurrentItem(0);
//					Log.i("hz", "has district");
//				} else {
//					Log.i("hz", "no district");
//					ArrayList<BeanAreaDistrict> array = new ArrayList<BeanAreaDistrict>();
//					BeanAreaDistrict district = new BeanAreaDistrict();
//					district.districtName = mProvinces.get(mProvinceValue)
//							.cityList.get(newValue).cityName;
//					array.add(district);
//					mWheelQu.setAdapter(new DistrictWheelAdapter(array));
//					mWheelQu.setCurrentItem(0);
//				}

				String shiExtraTemp = "0"+","+provinceList.get(mProvinceValue).Id;
				ArrayList<BeanArea> shiListTemp = BeanArea.getAreaByExtra(shiExtraTemp);

				String quExtraTemp = shiExtraTemp+","+shiListTemp.get(newValue).Id;
				ArrayList<BeanArea> quListTemp = BeanArea.getAreaByExtra(quExtraTemp);

				if (quListTemp != null && quListTemp.size() != 0) {
					mWheelQu.setAdapter(new DistrictWheelAdapter(quListTemp));
					mWheelQu.setCurrentItem(0);
					Log.i("hz", "has district");
				} else {
					Log.i("hz", "no district");
					ArrayList<BeanArea> array = new ArrayList<BeanArea>();
					BeanArea district = new BeanArea();
					district.Name = shiListTemp.get(newValue).Name;
					array.add(district);
					mWheelQu.setAdapter(new DistrictWheelAdapter(array));
					mWheelQu.setCurrentItem(0);
				}
			}
		};

		OnWheelChangedListener districtListner = new OnWheelChangedListener() {
			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				mDistrictValue = newValue;
			}
		};

		mWheelProvince.addChangingListener(provinceListner);
		mWheelCity.addChangingListener(cityListner);
		mWheelQu.addChangingListener(districtListner);

		TextView okTextView = (TextView) view.findViewById(R.id.okTextView);
		okTextView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				myDialog.dismiss();
				getAreaInfo();
			}
		});

		myDialog.addView(view);
		myDialog.create(null);
		myDialog.showMyDialog();
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	@Override
	public void RequestComplete(Object object, Object data) {
		hideProgressDialog();
		finish(true);

		ObserverManager.getInstance().notify(
				ObserverConst.NOTIFY_MY_ADDRESS_MANAGE_CHANGE, null, null);
	}

	@Override
	public void RequestError(Object object, int errorId, String data) {
		hideProgressDialog();
	}

	@Override
	public void onTopbarRightButtonSelected() {
		save();
	}

}
